

<template>
  <div>
    <div class="flex-input">
      <div>
        <el-input v-model="getListParme.name"   placeholder="单位名称" />
      </div>
      <div>
        <el-input v-model="getListParme.agerName"  placeholder="负责人" />
      </div>
      <div class="data-flex">
        <div>
          <el-date-picker
              v-model="valueDate"
              :type="year"
              range-separator="至"
              start-placeholder="成立时间"
              end-placeholder="成立时间"

          />
        </div>
        <div>
          <!--          <el-radio-group v-model="year" aria-label="size control">-->
          <!--            <el-radio-button value="daterange">年/月/日</el-radio-button>-->
          <!--            <el-radio-button value="monthrange">月</el-radio-button>-->
          <!--            <el-radio-button value="yearrange">年</el-radio-button>-->
          <!--          </el-radio-group>-->
          <div class="data-selete">
            <el-select
                v-model="year"
                placeholder="请选择"
                style="width: 80px"
                @change="valueDate=[]"
            >
              <el-option
                  v-for="item in optionsdata"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>

          </div>
        </div>
      </div>
      <div style="min-width: 180px; text-align: center">
        <el-button icon="ArrowLeft"  @click="searchOpen = !searchOpen">更多</el-button>
<!--        <el-button icon="ArrowLeft" @click="drawer = true">更多</el-button>-->
        <el-button type="primary" icon="Search" @click="confirmClick">查询</el-button>
      </div>

    </div>
    <div v-show="searchOpen" class="sss">
      <el-input
          v-model="getListParme.code"
          placeholder="单位编号"
      />
      <el-select
          multiple
          collapse-tags
          filterable
          collapse-tags-tooltip
          v-model="getListParme.unitTypeIdList"
          placeholder="单位类型"
          @focus="getdanweileixingOptions"
      >
        <el-option
            v-for="item in danweileixingOptions"
            :key="item.name"
            :label="item.name"
            :value="item.code"
        />
      </el-select>
      <el-input
          v-model="getListParme.linkMan"
          placeholder="联系人"
      />
      <el-input
          v-model="getListParme.tel"
          placeholder="联系电话"
      />
      <el-input
          v-model="getListParme.intro"
          placeholder="简介"
      />
      <el-input
          v-model="getListParme.standBY1"
          placeholder="备注"
      />

        <el-input
            v-model="getListParme.startOrderId"
            placeholder="最小排序号"
        />至
        <el-input
            v-model="getListParme.lastOrderId"
            placeholder="最大排序号"
        />


    </div>
    <div>
      <el-table
          border
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          row-key="id"
          default-expand-all
          lazy
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'isExist' }"
      >
        <el-table-column type="selection"  width="55" />
        <el-table-column label="单位名称">
          <template #default="scope">
            <span style="cursor: pointer;color: #2A91FE" @click="dialogopenunitdetails(scope.row)">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column property="agerName" label="负责人"/>
        <el-table-column label="科研人员" >
        <template #default="scope">
          <div style="cursor: pointer;color: #2A91FE" @click="openpeopledetails(scope.row)">{{ scope.row.count }}</div>
        </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" >
          <template #default="scope">
            <el-button v-if="scope.row.isLevel == 0" link type="primary" size="small"  @click="handleClick(scope.row)">
              编辑
            </el-button>
            <el-button link type="primary" size="small" v-if="scope.row.isLevel==0"   @click="addTwo(scope.row,0)">
              添加二级
            </el-button>
            <el-button link type="primary" size="small" v-if="scope.row.isLevel==1"   @click="addTwo(scope.row,1)">
              编辑二级
            </el-button>
            <el-button link type="primary" size="small"  @click="TableDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="example-pagination-block">
      <el-pagination
          layout="->,prev, pager, next, total"
          :total="count"
          currentPage1="10"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!--  更多-->
  <el-drawer v-model="drawer" :direction="direction">
    <template #header>
      <h4>选择条件</h4>
    </template>
    <template #default>
      <div class="sss">
        <el-input
            v-model="getListParme.code"
            style="width: 200px"
            size="small"
            placeholder="单位编号"
        />
        <el-select
            multiple
            collapse-tags
            filterable
            collapse-tags-tooltip
            v-model="getListParme.unitTypeIdList"
            placeholder="单位类型"
            size="small"
            style="width: 200px"
            @focus="getdanweileixingOptions"
        >
          <el-option
              v-for="item in danweileixingOptions"
              :key="item.name"
              :label="item.name"
              :value="item.code"
          />
        </el-select>
        <el-input
            v-model="getListParme.linkMan"
            style="width: 200px"
            size="small"
            placeholder="联系人"
        />
        <el-input
            v-model="getListParme.tel"
            style="width: 200px"
            size="small"
            placeholder="联系电话"
        />
        <el-input
            v-model="getListParme.intro"
            style="width: 200px"
            size="small"
            placeholder="简介"
        />
        <el-input
            v-model="getListParme.standBY1"
            style="width: 200px"
            size="small"
            placeholder="备注"
        />
        <div>
          <el-input
              v-model="getListParme.startOrderId"
              style="width: 200px"
              size="small"
              placeholder="最小排序号"
          />至
          <el-input
              v-model="getListParme.lastOrderId"
              style="width: 200px"
              size="small"
              placeholder="最大排序号"
          />
        </div>

      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">关闭</el-button>
        <el-button type="primary" @click="confirmClick">查询</el-button>
      </div>
    </template>
  </el-drawer>
  <!--  更多-->
<!--  编辑-->
  <el-dialog v-model="dialogFormVisible" title="编辑" width="70%">
    <div>
      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >
        <div class="dialog-flex">
          <div>
            <el-form-item label="单位名称" prop="name">
              <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="负责人" prop="agerName">
              <el-input v-model="ruleForm.agerName" />
            </el-form-item>
            <el-form-item label="教育部统计" prop="subjectClassId">
              <el-radio-group v-model="ruleForm.subjectClassId"  @change="GetsubjectClassId(1)">
                <el-radio label="科技类" value="2"/>
                <el-radio label="社科类" value="1"/>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="一级学科" prop="subjectId" >
              <el-select
                  v-model="ruleForm.subjectId"
                  placeholder="请选择一级学科"
                  @focus="getyijixuekeOptions(1)"
              >
                <el-option
                    v-for="item in yijixuekeOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否统计" prop="isState">
              <el-radio-group v-model="ruleForm.isState">
                <el-radio label="统计" value="1"/>
                <el-radio label="不统计" value="0"/>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="批准机构" prop="approve">
              <el-select
                  v-model="ruleForm.approve"
                  placeholder="请选择批准机构"
              >
                <el-option key="学校主管部门批准" label="学校主管部门批准" value="学校主管部门批准"/>
                <el-option key="非学校主管部门批准" label="非学校主管部门批准" value="非学校主管部门批准"/>
                <el-option key="学校自建" label="学校自建" value="学校自建"/>
              </el-select>
            </el-form-item>


          </div>
          <div>
            <el-form-item label="联系人":label-width="formLabelWidth">
              <el-input v-model="ruleForm.linkMan" />
            </el-form-item>
            <el-form-item label="成立时间" :label-width="formLabelWidth">
              <el-date-picker
                  v-model="ruleForm.unitCreateDate"
                  type="date"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                  aria-label="选择时间"
                  placeholder="选择时间"
              />
            </el-form-item>
            <el-form-item label="单位编号" :label-width="formLabelWidth">
              <el-input v-model="ruleForm.code" autocomplete="off" />
            </el-form-item>
            <el-form-item label="单位类型" :label-width="formLabelWidth">
              <el-radio-group v-model="ruleForm.unitTypeId">
                <el-radio
                    v-for="item in danweileixingOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.code"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系电话" :label-width="formLabelWidth" prop="tel">
              <el-input v-model="ruleForm.tel" autocomplete="off" />
            </el-form-item>
            <el-form-item label="排序号" :label-width="formLabelWidth" prop="orderId">
              <el-input v-model.number="ruleForm.orderId" type="text" />
            </el-form-item>
          </div>
        </div>
        <div>
          <el-form-item label="简介" :label-width="formLabelWidth">
            <el-input v-model="ruleForm.intro" type="textarea" />
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input v-model="ruleForm.standBY1" type="textarea" />
          </el-form-item>
        </div>
        <div style="margin-left:35%">
          <el-form-item>
            <el-button style="text-align: center" type="primary" @click="submitForm(ruleFormRef)">
              保存
            </el-button>
            <el-button style="text-align: center" @click="resetForm(ruleFormRef,'closeone')">关闭</el-button>
          </el-form-item>
        </div>

      </el-form>
    </div>
  </el-dialog>
  <!--  编辑-->
  <!--  编辑二级单位-->
  <el-dialog v-model="dialogFormVisibleTwo" title="二级单位" width="70%">
    <div>
      <el-form
          ref="ruleFormRef"
          :model="ruleFormTwo"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >
        <div class="dialog-flex">
          <div>
            <el-form-item label="单位名称" prop="name">
              <el-input v-model="ruleFormTwo.name" />
            </el-form-item>
            <el-form-item label="负责人" prop="agerName">
              <el-input v-model="ruleFormTwo.agerName" />
            </el-form-item>
            <el-form-item label="教育部统计" prop="subjectClassId">
              <el-radio-group v-model="ruleFormTwo.subjectClassId" @change="GetsubjectClassId(2)">
                <el-radio label="科技类" value="2"/>
                <el-radio label="社科类" value="1"/>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="一级学科" prop="subjectId" >
              <el-select
                  v-model="ruleFormTwo.subjectId"
                  placeholder="请选择一级学科"
                  @focus="getyijixuekeOptions(2)"
              >
                <el-option
                    v-for="item in yijixuekeOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否统计" prop="isState">
              <el-radio-group v-model="ruleFormTwo.isState">
                <el-radio label="统计" value="1"/>
                <el-radio label="不统计" value="0"/>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="批准机构" prop="approve">
              <el-select
                  v-model="ruleFormTwo.approve"
                  placeholder="请选择批准机构"
              >
                <el-option key="学校主管部门批准" label="学校主管部门批准" value="学校主管部门批准"/>
                <el-option key="非学校主管部门批准" label="非学校主管部门批准" value="非学校主管部门批准"/>
                <el-option key="学校自建" label="学校自建" value="学校自建"/>
              </el-select>
            </el-form-item>

          </div>
          <div>

            <el-form-item label="联系人" :label-width="formLabelWidth">
              <el-input v-model="ruleFormTwo.linkMan" />
            </el-form-item>
            <el-form-item label="成立时间" :label-width="formLabelWidth">
              <el-date-picker
                  v-model="ruleFormTwo.unitCreateDate"
                  type="date"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                  aria-label="选择时间"
                  placeholder="选择时间"
              />
            </el-form-item>
            <el-form-item label="单位编号" :label-width="formLabelWidth">
              <el-input v-model="ruleFormTwo.code" autocomplete="off" />
            </el-form-item>
            <el-form-item label="单位类型" :label-width="formLabelWidth">
              <el-radio-group v-model="ruleFormTwo.unitTypeId">
                <el-radio
                    v-for="item in danweileixingOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.code"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系电话" :label-width="formLabelWidth" prop="tel">
              <el-input v-model="ruleFormTwo.tel" autocomplete="off" />
            </el-form-item>
            <el-form-item label="排序号" :label-width="formLabelWidth" prop="orderId">
              <el-input v-model.number="ruleFormTwo.orderId" type="text" />
            </el-form-item>
          </div>
        </div>
        <div>
          <el-form-item label="简介">
            <el-input v-model="ruleFormTwo.intro" type="textarea" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="ruleFormTwo.standBY1" type="textarea" />
          </el-form-item>
        </div>
        <div style="margin-left:35%">
          <el-form-item>
            <el-button style="text-align: center" type="primary" v-if="compiles == 0" @click="addTwobtn(ruleFormRef)">
              保存
            </el-button>
            <el-button style="text-align: center" type="primary" v-if="compiles == 1" @click="addTwobtncompiles(ruleFormRef)">
              保存
            </el-button>
            <el-button style="text-align: center" @click="resetForm(ruleFormRef ,'closetwo')">关闭</el-button>
          </el-form-item>
        </div>

      </el-form>
    </div>
  </el-dialog>
  <!--  编辑-->

  <el-dialog v-model="openListpeopledetailsVisible" title="成员查看" width="70%">
    <el-table :data="ListpeopledetailsData">
      <el-table-column label="职工号">
        <template #default="scope">{{ scope.row.account }}</template>
      </el-table-column>
      <el-table-column  label="姓名" >
        <template #default="scope" >
          <div style="cursor: pointer;color: #2A91FE" @click="dialogopenpeopledetails(scope.row)">{{ scope.row.name }}</div>
        </template>
      </el-table-column>

      <el-table-column property="titleName" label="职称" />
      <el-table-column property="firstLevel" label="一级学科" />
      <el-table-column property="eduDegreeId" label="最后学位" >
      <template #default="scope" >
        {{getEduDegreeName(scope.row.eduDegreeId)}}
      </template>
      </el-table-column>
      <el-table-column label="科研详情">
        <template #default="scope">
          <div style="cursor: pointer;color: #2A91FE">
            <span @click="GoDetailsPage(scope.row)">查看</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column property="unitName" label="所属单位" />
      <el-table-column   prop="checkstatus" label="审核状态">
        <template #default="{ row }">
          <CommonLabel
              :dataList="checkStatusList"
              valueKey="dictValue"
              labelKey="dictLabel"
              :value="row.checkstatus"
          />
        </template>
      </el-table-column>
    </el-table>
    <div class="example-pagination-block">

      <el-pagination
          layout="->,prev, pager, next, total"
          :total="countpeopleList"
          currentPage1="10"
          @size-change="handleSizeChangepeopleList"
          @current-change="handleCurrentChangepeopleList"
      />
    </div>
  </el-dialog>

  <zjrcpeopleDetails :activ="activ"  :obj="obj"  @close-dialog="activ = false"></zjrcpeopleDetails>
  <unitDetails :unitactiv="unitactiv"  :unitobj="unitobj"  @close-dialog="unitactiv = false"></unitDetails>
  <DetailsPageVue ref="DetailsPage"></DetailsPageVue>
</template>
<script lang="ts" setup>
const searchOpen = ref(false)
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import useDictFetch from "@/hooks/useDictFetch";
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
import {getCategory} from "@/api/researcherNavApi/researcherNavApi"
import zjrcpeopleDetails from './../../../components/peopleDetails/peopleDetails.vue'
import unitDetails from './../../../components/peopleDetails/unitDetails.vue'
import {
  selectOrganizationList,
  deleOrganizationList,
 organizationListDetails,
  updateOrganizationList,
  insertLevelOrganizationList,
  levelOrganizationList,
  deletLexelOrganizationList,
  getPersonList,
  exportList
} from '@/api/researcherNavApi/zzjgApi'
import {onBeforeMount, onMounted, reactive, ref} from "vue";
import {DrawerProps, ElMessage, ElMessageBox} from "element-plus";
import {before} from "lodash";
const drawer = ref(false) //更多在弹出
const direction = ref<DrawerProps['direction']>('rtl')
//跳转科研详情
import DetailsPageVue from '@/views/details/DialogdetailsPage.vue'
const DetailsPage = ref(null)
const GoDetailsPage = function (row){
  DetailsPage.value.openDialogDetailsPage(row.id)
}

const getEduDegreeName = (eduDegreeId) => {
  if (eduDegreeId === undefined || eduDegreeId == null) {
    return '未知';
  }
  const eduDegreeMap = {
    2: '博士',
    3: '硕士',
    4: '学士',
    999: '无'
  };
  return eduDegreeMap[eduDegreeId] || '未知';
};
//导出
import {handleFileDownload} from './../../../utils/downloadSz'
const Export = () => {
  // 复制一份 getListParme 对象， 避免修改原始数据
  //const requestData = { ...getListParme.value };
  exportList({   ...getListParme.value}

  )
      .then((res)=>{
        if (res.code === 500) {
          ElMessage({
            type: 'error',
            message: '数据库查询出错，请联系管理员检查 SQL 语句。'
          });
        } else if (!(res instanceof Blob)) {
          ElMessage({
            type: 'info',
            message: '响应数据不是 Blob 类型',
          })
        }else {
          handleFileDownload(res, '组织结构 单位列表');
        }
      })
}
//单位详情
const unitactiv = ref(false)
const unitobj = ref('')
const dialogopenunitdetails = function (row){
  unitactiv.value = true
  console.log(unitactiv.value)
  unitobj.value = row.id
}
const  GetsubjectClassId = function (key){
  if(key == 1){
    ruleForm.subjectId = ''
  }else {
    ruleFormTwo.subjectId = ''
  }

}
//一级学科
const yijixuekeOptions = ref([])
const getyijixuekeOptions =function (key) {
  //一级单位
  if(key == 1){
    getCategory(
        {
          'bizName':'一级学科',
          valueCascade: ruleForm.subjectClassId
        }
    )
        .then((res)=>{

          yijixuekeOptions.value = res.data
        })
  }else {
    getCategory(
        {
          'bizName':'一级学科',
          valueCascade: ruleFormTwo.subjectClassId
        }
    )
        .then((res)=>{

          yijixuekeOptions.value = res.data
        })
  }

}
//人数分页
const handleSizeChangepeopleList = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChangepeopleList = function (val){
  getPersonList({
    unitId:peopleListRow.value,
    page:val,
    pageSize:10,
  })
      .then((res)=>{
        if(res.code ==200){
          openListpeopledetailsVisible.value = true
          ListpeopledetailsData.value = res.data.list
          countpeopleList.value = res.data.count
        }
      })

}


//人名弹窗
///查看详情
const activ = ref(false)
const obj = ref('')
const dialogopenpeopledetails = function (row){
  activ.value = true
  console.log(activ.value)
  obj.value = row.id
}
//人数列表
const peopleListRow = ref('')
const countpeopleList = ref(0)
const openListpeopledetailsVisible = ref(false)
const ListpeopledetailsData = ref([])
const openpeopledetails = function (row){
  peopleListRow.value = row.id

  getPersonList({
    unitId:row.id,
    page:1,
    pageSize:10,
  })
      .then((res)=>{
        if(res.code ==200){

          openListpeopledetailsVisible.value = true
          ListpeopledetailsData.value = res.data.list
          countpeopleList.value = res.data.count
        }
      })
}
//人数列表end
//新增二级单位
const dialogFormVisibleTwo = ref(false)
interface RuleForm {
  name: string
  agerName: string
  subjectClassId: string
  subjectId: string
  isState: string
  approve: string
  linkMan: string
  unitCreateDate: string
  code: string
  unitTypeId: string
  tel: string
  orderId: string
  intro: string
  standBY1: string
}
const ruleFormTwo = reactive<RuleForm>({
  name:'', //单位名称
  agerName:'', //负责人
  linkMan:'', //联系人
  unitCreateDate:'',  //;成立时间
  subjectClassId:'2',  //;教育部统计
  subjectId:'',  //;一级学科
  isState:'',  //;是否统计
  approve:'',  //;批准机构

  code:'',   //;单位编号
  unitTypeId:'', //单位类型
  tel:'', //联系电话
  orderId:'',  //; 排序号

  intro:'', //;简介
  standBY1:'', //;备注
})
// 编辑二级保存
const addTwobtncompiles = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  try {
    // 等待验证完成
    const valid = await formEl.validate();
    if (valid) {
      console.log(ruleFormTwo);
      updateOrganizationList(ruleFormTwo)
          .then((res) => {
            if (res.code == 200) {
              ElMessage({
                type: 'success',
                message: res.data,
              });
              confirmClick();
             // alert('confirmClick')
              refresh(ruleFormTwo.upUnitId);
             // alert('refresh')
              dialogFormVisibleTwo.value = false;
            } else {
              ElMessage({
                type: 'info',
                message: res.msg,
              });
            }
          });
    }
  } catch (error) {
    console.log('error submit!', error);
  }
};

// 新增保存
const addTwobtn = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  try {
    // 等待验证完成
    const valid = await formEl.validate();
    if (valid) {
      console.log(ruleFormTwo);
      insertLevelOrganizationList(ruleFormTwo)
          .then((res) => {
            if (res.code == 200) {
              ElMessage({
                type: 'success',
                message: res.data,
              });
              confirmClick();
              refresh(ruleFormTwo.upUnitId);
              dialogFormVisibleTwo.value = false;
            } else {
              ElMessage({
                type: 'info',
                message: res.msg,
              });
            }
          });
    }
  } catch (error) {
    console.log('error submit!', error);
  }
};


const compiles = ref(1)
const addTwo = function (row,compile) {
  //compile 0新增 1 编辑
  if(compile == 0){
    dialogFormVisibleTwo.value = true
    getdanweileixingOptions()
    Object.assign(ruleFormTwo, {
      upUnitId:row.id,
      name: '', //单位名称
      agerName:'', //负责人
      subjectClassId:'2',  //;教育部统计
      subjectId:'',  //;一级学科
      isState:'',  //;是否统计
      approve:'',  //;批准机构
      linkMan:'',//联系人
      unitCreateDate: '',//成立时间
      code:'',//单位编号
      unitTypeId:'',//单位类型
      tel: '',  //联系电话.
      orderId:Number(),//排序号
      intro:'',//简介
      standBY1:'',//备注
      // id:row.id
    });

    compiles.value = compile
  }else {
    dialogFormVisibleTwo.value = true
    getdanweileixingOptions()
    organizationListDetails({id:row.id})
        .then((res)=>{
          Object.assign(ruleFormTwo, {
            upUnitId:res.data[0].upUnitId,
            name: res.data[0].name, //单位名称
            agerName:res.data[0].agerName, //负责人
            subjectClassId:res.data[0].subjectClassId, //教育部统计
            subjectId:res.data[0].subjectId, //一级学科
            isState:res.data[0].isState, //是否统计
            approve:res.data[0].approve, //批准机构
            linkMan:res.data[0].linkMan,//联系人
            unitCreateDate: res.data[0].unitCreateDate,//成立时间
            code:res.data[0].code,//单位编号
            unitTypeId:res.data[0].unitTypeId,//单位类型
            tel: res.data[0].tel,  //联系电话.
            orderId:Number(res.data[0].orderId),//排序号
            intro:res.data[0].intro,//简介
            standBY1:res.data[0].standBY1,//备注
            id:row.id
          });
        })
    compiles.value = compile
  }



}
const maps = new Map()
const tableRef = ref(null);
const load = (row, treeNode, resolve) => {
  setTimeout(() => {
    maps.set(row.id, {row, treeNode, resolve})
    levelOrganizationList({ upUnitId: row.id })
        .then((res) => {
          console.log(res);
          const children = res.data.map(item => {
            // 假设树形表格要求每个节点有一个 children 字段
            item.children = [];
            return item;
          });
          console.log(children);
          resolve(children);
        })
        .catch((error) => {
          console.error('加载子节点数据失败:', error);
          resolve([]);
        });
  }, 1000);
};
const refresh = (parentId) => {
  const map = maps.get(parentId);
  //alert('jinlerefresh')
  if(map) {
    load(map.row, map.treeNode,map.resolve)
  }
}




//分页
const count = ref(0)

//初始化请求
const getListParme = ref({
  name:'', //单位名称
  agerName:'', //负责人
  startDate:'',  //;初始时间
  lastDate:'',   //;结束时间
  code:'', //单位编号
  unitTypeIdList:[], //单位类型
  tel:'', //联系电话
  linkMan:'', //联系人
  intro:'', //;简介
  standBY1:'', //;备注
  startOrderId:'',  //;最小序号
  lastOrderId:'',  //;最大序号


  page:1,
  pageSize:10

})
//单位类型
const danweileixingOptions = ref()
const getdanweileixingOptions =function () {
  getCategory(
      {
        'bizName':'单位类型'
      }
  )
      .then((res)=>{

        danweileixingOptions.value = res.data
      })
}

//单位类型end

function cancelClick() {
  drawer.value = false
};
// utils/dateFormat.js
// 在组件中添加此方法
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
//查询
function confirmClick() {
  console.log(valueDate.value)
  if (valueDate.value && valueDate.value.length === 2) {
    // 根据选择类型处理日期范围
    if (year.value === 'daterange') {
      // 按日选择（保持原有逻辑）
      getListParme.value.startDate = formatDate(valueDate.value[0]);
      getListParme.value.lastDate = formatDate(valueDate.value[1]);
    } else if (year.value === 'monthrange') {
      // 按月选择：计算当月第一天和最后一天
      const startMonth = new Date(valueDate.value[0]);
      const endMonth = new Date(valueDate.value[1]);

      // 开始日期：当月第一天
      const startDate = new Date(startMonth.getFullYear(), startMonth.getMonth(), 1);

      // 结束日期：当月最后一天（下个月第一天减1天）
      const endDate = new Date(endMonth.getFullYear(), endMonth.getMonth() + 1, 0);

      // 转换为 YYYY-MM-DD 格式
      getListParme.value.startDate = formatDate(startDate);
      getListParme.value.lastDate = formatDate(endDate);
    } else if (year.value === 'yearrange') {
      // 按年选择（保持原有逻辑）
      const startYear = valueDate.value[0].getFullYear();
      const endYear = valueDate.value[1].getFullYear();

      getListParme.value.startDate = `${startYear}-01-01`;
      getListParme.value.lastDate = `${endYear}-12-31`;
    }
  }else {
    getListParme.value.startDate = ''
    getListParme.value.lastDate = ''
  }
  selectOrganizationList(getListParme.value)
      .then((res)=>{
        tableData.value = res.data.list
        count.value = res.data.count
      })


}
//清空弹框
const clearParams = () => {
  const params = getListParme.value
  for (const key in params) {
    if (key === 'page' || key === 'pageSize') continue // 跳过分页参数
    if (Array.isArray(params[key])) {
      params[key] = []
    } else if (typeof params[key] === 'number') {
      params[key] = 0
    } else {
      params[key] = ''
    }
  }
}


const optionsdata = [
  {
    value: 'daterange',
    label: '年/月/日',
  },
  {
    value: 'monthrange',
    label: '月',
  },
  {
    value: 'yearrange',
    label: '年',
  },

]
//编辑回限
const handleClick = (row) => {
  dialogFormVisible.value = true
  getyijixuekeOptions()
  getdanweileixingOptions()
  organizationListDetails({id:row.id})
      .then((res)=>{
        Object.assign(ruleForm, {
          name: res.data[0].name, //单位名称
          agerName:res.data[0].agerName, //负责人
          subjectClassId:res.data[0].subjectClassId, //教育部统计
          subjectId:res.data[0].subjectId, //一级学科
          isState:res.data[0].isState, //是否统计
          approve:res.data[0].approve, //批准机构
          linkMan:res.data[0].linkMan,//联系人
          unitCreateDate: res.data[0].unitCreateDate,//成立时间
          code:res.data[0].code,//单位编号
          unitTypeId:res.data[0].unitTypeId,//单位类型
          tel: res.data[0].tel,  //联系电话.
          orderId: res.data[0].orderId != null?Number(res.data[0].orderId):'',//排序号
          intro:res.data[0].intro,//简介
          standBY1:res.data[0].standBY1,//备注
          id:row.id
        });
      })
}
const tableData = ref([])
// 删除
const TableDelete = function (row) {
  console.log(row.isLevel)
  if(row.count != 0 ){
    ElMessage({
      type: 'warning',
      message: '有人员归厘于该单位，单位无法删除!',
    })
    return
  }
  if(row.isLevel == 0){
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          deleOrganizationList({'idList':[row.id]})
              .then((res)=>{
                if(res.code==200){
                  ElMessage({
                    type: 'success',
                    message: res.data,
                  })
                  confirmClick()
                }else {
                  ElMessage({
                    type: 'info',
                    message: res.msg,
                  })
                }
              })
        })
        .catch(() => {
          // ElMessage({
          //   type: 'info',
          //   message: 'Delete canceled',
          // })
        })
  }else {
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          let deleteArr = []
          for (let i = 0; i < multipleSelection.value.length; i++) {
            deleteArr.push(multipleSelection.value[i].id)
          }
          deletLexelOrganizationList({'id':row.id,'upUnitId':row.upUnitId})
              .then((res)=>{
                if(res.code==200){
                  confirmClick()
                  refresh(row.upUnitId);
                  ElMessage({
                    type: 'success',
                    message: res.data,
                  })
                }else {
                  ElMessage({
                    type: 'info',
                    message: res.msg,
                  })
                }
              })
        })
        .catch(() => {
          // ElMessage({
          //   type: 'info',
          //   message: 'Delete canceled',
          // })
        })
  }


}


// 删除end
//批量删除
const multipleSelection = ref([])
const handleSelectionChange = (val) => {

  multipleSelection.value = val
  console.log(val,'console.log(handleSelectionChange)')
}


const open = () => {
  if(multipleSelection.value.length < 1){
    ElMessage({
      type: 'warning',
      message: '请选择想要删除的数据',
    })
  }else {
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          let deleteArr = []
          for (let i = 0; i < multipleSelection.value.length; i++) {
            deleteArr.push(multipleSelection.value[i].id)
          }
          deleOrganizationList({'idList':deleteArr})
              .then((res)=>{
                if(res.code==200){
                  ElMessage({
                    type: 'success',
                    message: res.data,
                  })
                  confirmClick()
                }else {
                  ElMessage({
                    type: 'info',
                    message: res.msg,
                  })
                }
              })
        })
        .catch(() => {
          // ElMessage({
          //   type: 'info',
          //   message: 'Delete canceled',
          // })
        })
  }


}
// 批量删除end

// 编辑
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const form = reactive({
  name: '',
  region: '',
  type: [],
  resource: '',
  desc: '',
})
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name:'', //单位名称
  agerName:'', //负责人
  linkMan:'', //联系人
  unitCreateDate:'',  //;成立时间
  subjectClassId:'',  //;教育部统计
  subjectId:'',  //;一级学科
  isState:'',  //;是否统计
  approve:'',  //;批准机构

  code:'',   //;单位编号
  unitTypeId:'', //单位类型
  tel:'', //联系电话
  orderId:'',  //; 排序号

  intro:'', //;简介
  standBY1:'', //;备注
})

interface RuleForm {
  name: string
  agerName: string
  subjectClassId: string
  subjectId: string
  isState: string
  approve: string
  linkMan: string
  unitCreateDate: string
  code: string
  unitTypeId: string
  tel: string
  orderId: string
  intro: string
  standBY1: string
}
const checkAge = (rule: any, value: any, callback: any) => {
  if (value === '' || value === null || value === undefined) {
    // 如果值为空，直接通过验证
    callback();
  } else if (!Number.isInteger(Number(value))) {
    // 如果值不为空且不是整数，验证失败
    callback(new Error('请输入数字'));
  } else {
    // 如果值不为空且是整数，通过验证
    callback();
  }
  // setTimeout(() => {
  //   if (!Number.isInteger(value)) {
  //     callback(new Error('请输入数字,不可为0'))
  //   } else {
  //     callback()
  //   }
  // }, 1000)
}
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入单位名称', trigger: 'blur' },
  ],
  agerName: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
  ],
  orderId: [{ validator: checkAge, trigger: 'blur' }],
  tel: [
    {
      validator: (rule, value, callback) => {
        if (value && value.length > 11) {
          callback(new Error('联系电话最长为 11 位'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  try {
    // 等待验证完成
    const valid = await formEl.validate();
    if (valid) {
      console.log(ruleForm);
      updateOrganizationList(ruleForm)
          .then((res) => {
            if (res.code == 200) {
              ElMessage({
                type: 'success',
                message: res.data,
              });
              confirmClick();
              dialogFormVisible.value = false;
            } else {
              ElMessage({
                type: 'info',
                message: res.msg,
              });
            }
          });
    }
  } catch (error) {
    console.log('error submit!', error);
  }
};

const resetForm = (formEl: FormInstance | undefined , close) => {
  if (!formEl) return
  formEl.resetFields()
  if( close && close =='closeone'){
    dialogFormVisible.value = false
  }else if( close && close =='closetwo'){
    dialogFormVisibleTwo.value = false
  }
}
// 编辑
//年月日
// const size = ref<'default' | 'large' | 'small'>('default')
const year = ref<'daterange' | 'monthrange' | 'yearrange'>('daterange')

const valueDate = ref([])
// 公开给他爹
const fathergeilist = function (){
  // console.log(getListParme.value)
  if (valueDate.value && valueDate.value.length === 2) {
    // 将选择的年份范围设置为1月1号
    valueDate.value = [
      new Date(valueDate.value[0].getFullYear(), 0, 1),
      new Date(valueDate.value[1].getFullYear(), 0, 1)
    ];
    getListParme.value.startDate = valueDate.value[0]
    getListParme.value.lastDate = valueDate.value[1]
  }else {
    // 如果 valueDate 为空，将 beginTime 和 endTime 置为空字符串
    getListParme.value.startDate = '';
    getListParme.value.lastDate = '';
  }
  console.log(getListParme.value)
  selectOrganizationList(getListParme.value)
      .then((res)=>{
        tableData.value = res.data.list
        count.value = res.data.count
      })
}
defineExpose({open,fathergeilist,Export})
onBeforeMount(()=>{
  confirmClick()
  //  console.log(getListParme.value)
  // if (valueDate.value && valueDate.value.length === 2) {
  //   // 将选择的年份范围设置为1月1号
  //   valueDate.value = [
  //     new Date(valueDate.value[0].getFullYear(), 0, 1),
  //     new Date(valueDate.value[1].getFullYear(), 0, 1)
  //   ];
  //   getListParme.value.startDate = valueDate.value[0]
  //   getListParme.value.lastDate = valueDate.value[1]
  // }
 // console.log(getListParme.value,'onMounted')
 //  selectOrganizationList(getListParme.value)
 //      .then((res)=>{
 //        tableData.value = res.data.list
 //        count.value = res.count
 //      })

})
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}

const handleCurrentChange = function (val){
  console.log(`current page: ${val}`)

  getListParme.value.page = val
  selectOrganizationList(getListParme.value)
      .then((res)=>{
        tableData.value = res.data.list
        count.value = res.data.count
      })

}


</script>

<style scoped lang="scss">

.flex-input{
  display: flex;
  margin: 10px 5px 10px 0;
}
.flex-input > div{
  margin-right: 10px;
  width: 50%;
}
.sss > div{
  margin: 5px 3px;
  width: 19%;
}
.dialog-flex{
  display: flex;
}
.dialog-flex > div{
  width: 50%;
}
.data-flex{
  display: flex;
  min-width: 420px;
  margin: 0 3px;
}
.data-selete{
 width: 60px;
}
</style>